package com.cloudfun.campusshare.util;

import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by Huqin on 2020/3/11
 */
public class QueryUtil {

    public static Object getSingleResult(Query query) {
        List resultList = query.getResultList();
        if (resultList.size() == 1) {
            return resultList.get(0);
        } else if (resultList.size() > 1) {
            throw new NonUniqueResultException();
        } else {
            return null;
        }
    }

    public static <T> T getSingleResult(Query query, T defaultVal) {
        List resultList = query.getResultList();
        if (resultList.size() == 1) {
            return resultList.get(0) == null ? defaultVal : (T) resultList.get(0);
        } else if (resultList.size() > 1) {
            throw new NonUniqueResultException();
        } else {
            return defaultVal;
        }
    }
}
